package com.example.demo.realm;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;

import javax.annotation.Resource;
import java.util.Collection;


public class UserRealm extends AuthorizingRealm {
    private SessionDAO sessionDAO;
    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //认证
        String username = (String) authenticationToken.getPrincipal();
//        Collection<Session> activeSessions = sessionDAO.getActiveSessions();
//        for (Session session : activeSessions) {
//            String loginedusername = (String) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
//            if (username.equals(loginedusername)) {
//                session.setTimeout(0);
//                break;
//            }
//        }
        //通过username 到数据库取出用户对象(用户名密码)
        User user = userService.getUser(username);
        if ("用户对象不为空" != null) {
            return new SimpleAuthenticationInfo(username, user.getPassword(), "userRealm");
        }
        return null;
    }
}
